function success = SK6_Start( command , COM_PORT , sCFG )
% SHAKE SK6 Matlab Driver v1.00, (c) 2010 SAMH Engineering Services
%
% function success = SK6_Start( command , COM_PORT , sCFG )
% The top function of the SK6 Matlab Driver, it is used to both start
% a connection to the SK6 and close the connection when it is no longer
% required.
%
% if <command> = 'open':
% Open the SK6, configure it for the required output data parameters and
% parse all the data received and add it to a set of global FIFO circular
% buffers. The receive data parsing occurs in the background in conjunction
% with the call back function SK6_Recieve_Data_Parse_Callback(). 
%
% if <command> = 'close':
% Before your application exits, use this to close the connection to the
% SK6
% so that a subsequent 'open' will succeed.
%
% <COM_PORT> is the ASCII string that identifies the COM port, i.e. 'COM15'.
%
% <sCFG> is an optional argument that contains configuration data for
% the SK6. If this argument is not supplied then the configuration will 
% be based on the values contained in the file SK6_Config.m 
% See SK6_Config.m for details on the members of the sCFG structure.
% 
% If the command was successful then true is returned, otherwise false is returned.
%
% example usage :
% SK6_Start( 'open' , 'COM15' );
% SK6_Start( 'close' , '' );




% port is declared global so that if the driver code crashes, then you can call
% SK6_Close( port ) in the Matlab command window to release the serial port
global port


success = true;

switch command
  case 'close'
    SK6_Close();
    return;
    
  case 'open'
    clear SK6_Recieve_Data_Parse_Callback;
    clear global num_sensors;
    global num_sensors
    
    port = SK6_Open( COM_PORT );
    
    % configure the SK6
    if nargin == 2
    sk6_config = SK6_Config();
  	elseif nargin == 3
  	sk6_config = SK6_Config( sCFG );
    end
    
    [ sr sc ] = size( sk6_config );
    for cc = 3 : sr
      SK6_Write( char(sk6_config( cc , 1 )) , char(sk6_config( cc , 2 )) );
    end
    
    % wait a few miliseconds for the SK6 to update ( and ODRs to settle )
    pause( 0.1 );
    
    % wait until the receive callback function has been called for the first time
    while isempty( num_sensors )
    end
    
    return;
    
  otherwise
    % not a valid command, return false
    error ' Not a valid command to SK6_Start, please use either 'open' or 'close' '
    success = false;
    return;
end


end
